package com.fm.financemanage.controller.sys;


import com.fm.financemanage.component.TokenComponent;
import com.fm.financemanage.constant.UserConstants;
import com.fm.financemanage.model.po.SysMenu;
import com.fm.financemanage.model.po.SysUser;
import com.fm.financemanage.model.vo.Ztree;
import com.fm.financemanage.response.Callback;
import com.fm.financemanage.response.JsonData;
import com.fm.financemanage.service.SysMenuService;
import com.fm.financemanage.util.AuthorizationUtils;
import com.fm.financemanage.utils.TextUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author zpc
 * @version V1.0
 * @date 2021-05-12
 */
@Api(tags = "【web端】菜单权限")
@RestController
@RequestMapping("/sys/menu")
public class SysMenuController {

    @Autowired
    private SysMenuService menuService;
    @Autowired
    private TokenComponent tokenComponent;

    @RequiresPermissions(value = {"sys:menu:get"})
    @ApiOperation("查询所有菜单")
    @GetMapping("/")
    public JsonData list(HttpServletRequest request, HttpServletResponse response,
                         @RequestParam(name = "menuName", required = false) String menuName,
                         @RequestParam(name = "visible", required = false) Integer visible) {


        List<SysMenu> menuList = menuService.selectMenuList(menuName, visible);
        return Callback.success("200", "成功", menuList);

    }

    /**
     * 删除菜单
     */
    @RequiresPermissions(value = {"sys:menu:delete"})
    @ApiOperation("删除菜单")
    @DeleteMapping("/{menuId}")
    public JsonData remove(@PathVariable("menuId") Long menuId) {


        if (menuService.selectCountMenuByParentId(menuId) > 0) {
            return Callback.fail("505", "存在子菜单,不允许删除");
        }
        if (menuService.selectCountRoleMenuByMenuId(menuId) > 0) {
            return Callback.fail("505", "菜单已分配,不允许删除");
        }
        menuService.deleteMenuById(menuId);
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return Callback.success("200", "删除成功");

    }

    /**
     * 新增保存菜单
     */
    @RequiresPermissions(value = {"sys:menu:post"})
    @ApiOperation("新增保存菜单")
    @PostMapping("/")
    public JsonData addSave(HttpServletRequest servletRequest, @RequestBody SysMenu menu) {


        if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return Callback.fail("505", "新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        String authorization = servletRequest.getHeader("Authorization");
        SysUser byToken = tokenComponent.getByToken(authorization);
        if (byToken == null || TextUtil.isEmpty(byToken.getId())) {
            return Callback.fail("404", "暂无用户信息");
        }
        menu.setCreateBy(byToken.getLoginName());
        menuService.insertMenu(menu);
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return Callback.success("200", "添加成功");


    }

    /**
     * 修改保存菜单
     */
    @RequiresPermissions(value = {"sys:menu:put"})
    @ApiOperation("修改保存菜单")
    @PutMapping("/")
    public JsonData editSave(HttpServletRequest servletRequest, @RequestBody SysMenu menu) {


        if (UserConstants.MENU_NAME_NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return Callback.fail("505", "修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        }
        String authorization = servletRequest.getHeader("Authorization");
        SysUser byToken = tokenComponent.getByToken(authorization);
        if (byToken == null || TextUtil.isEmpty(byToken.getId())) {
            return Callback.fail("404", "暂无用户信息");
        }
        menu.setCreateBy(byToken.getLoginName());
        menuService.updateMenu(menu);
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return Callback.success("200", "修改成功");


    }

    /**
     * 加载角色菜单列表树
     */
    @RequiresPermissions(value = {"sys:menu:role:get"})
    @ApiOperation("加载角色菜单列表")
    @GetMapping("/role")
    public JsonData roleMenuTreeData(HttpServletRequest servletRequest, Long roleId) {

        String authorization = servletRequest.getHeader("Authorization");
        SysUser byToken = tokenComponent.getByToken(authorization);
        if (byToken == null || TextUtil.isEmpty(byToken.getId())) {
            return Callback.fail("404", "暂无用户信息");
        }
        List<Ztree> ztrees = menuService.roleMenuTreeData(roleId, null);
        return Callback.fail("200", "成功", ztrees);

    }

    /**
     * 新增保存菜单
     */
    @RequiresPermissions(value = {"sys:menu:import:post"})
    @ApiOperation("导入菜单")
    @PostMapping("/import")
    public JsonData importMenu(HttpServletRequest servletRequest, @RequestBody List<SysMenu> menus) {

        String authorization = servletRequest.getHeader("Authorization");
        SysUser byToken = tokenComponent.getByToken(authorization);
        if (byToken == null || TextUtil.isEmpty(byToken.getId())) {
            return Callback.fail("404", "暂无用户信息");
        }
        menuService.importMenu(menus, byToken.getLoginName());
        AuthorizationUtils.clearAllCachedAuthorizationInfo();
        return Callback.success("200", "添加成功");
    }

    /**
     * 新增保存菜单
     */
    @RequiresPermissions(value = {"sys:menu:export:get"})
    @ApiOperation("导出菜单")
    @GetMapping("/export")
    public JsonData exportMenu(HttpServletRequest servletRequest, HttpServletResponse response) {
        List<SysMenu> all = menuService.getAll();

        return Callback.success("200", "导出成功", all);


    }
}
